#!/usr/bin/env python

import fgrepwc
import os
import sys

# recursively invoke fgrepwc for all the filenames and directories within this directory
def fgrepwcdirectory(word, directory=os.getcwd(), caseSens=True):

    if directory.endswith("/"):
        directory = directory[:len(directory)-1]
    os.chdir(directory)
    dirList = os.listdir(os.getcwd())

    subdirs = []
    for fileName in dirList:
        if os.path.isdir(fileName): # if fileName is a directory, store in temporary list
            subdirs.append(fileName)
        else:
            print "In file: " + directory + "/" + fileName
            fgrepwc.filefind(word, fileName, caseSens)

    # recurse for all elements in temporary list
    for subdir in subdirs:
        fgrepwcdirectory(word, directory + "/" + subdir, caseSens)

if len(sys.argv) > 2:

    caseSens = True
    # argument index
    i = 1
    if len(sys.argv) == 4:
        if sys.argv[1] == "-i":
            i = i + 1
            caseSens = False
        else:
            fgrepwc.usage();

    print str(caseSens) + " "  + sys.argv[i] + " "  + sys.argv[i+1];

    if os.path.isdir(sys.argv[i+1]):
        fgrepwcdirectory(sys.argv[i], sys.argv[i+1], caseSens)
    else:
        fgrepwc.filefind(sys.argv[i], sys.argv[i+1], caseSens)
else:
    fgrepwc.usage()
